package com.xpgk.config;

import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.wall.WallConfig;
import com.alibaba.druid.wall.WallFilter;
import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.plugin.ehcache.EhCachePlugin;
import com.jfinal.template.Engine;
import com.xpgk.constant.ConstantCache;
import com.xpgk.constant.ConstantInit;
import com.xpgk.dto.DataBase;
import com.xpgk.handler.GlobalHandler;
import com.xpgk.handler.WebSocketHandler;
import com.xpgk.interceptor.AuthInterceptor;
import com.xpgk.interceptor.ParamPkgInterceptor;
import com.xpgk.mvc.image.AuthImgController;
import com.xpgk.mvc.index.IndexController;
import com.xpgk.mvc.login.LoginController;
import com.xpgk.plugin.FileRenamePlugin;
import com.xpgk.plugin.ParamInitPlugin;
import com.xpgk.plugin.ServicePlugin;
import com.xpgk.plugin.SqlXmlPlugin;
import com.xpgk.tools.ToolBeetl;
import com.xpgk.tools.ToolCache;
import com.xpgk.tools.ToolDataBase;

public class Config extends JFinalConfig {

	private static final Log log = Log.getLog(Config.class);

	/**
	 * 配置常量
	 */
	@Override
	public void configConstant(Constants constants) {
		log.info("configConstant 缓存 properties");
		PropKit.use("init.properties");

		log.info("configConstant 设置字符集");
		constants.setEncoding("UTF-8");

		log.info("configConstant 设置是否开发模式");
		constants.setDevMode(PropKit.getBoolean(ConstantInit.config_devMode, false));

		log.info("configConstant 视图Beetl设置");
		ToolBeetl.brf.config();
		constants.setRenderFactory(ToolBeetl.brf);
		ToolBeetl.regiseter();

		log.info("configConstant 视图error page设置");
		constants.setError404View("/common/404.html");
		constants.setError500View("/common/500.html");

		log.info("configConstant formTaken缓存目标"); // JFinal默认缓存到session，本系统未启用session，所以默认是ehcache
		if (ToolCache.getCacheType().equals(ConstantCache.cache_type_ehcache)) {
			constants.setTokenCache(new FormTokenByEhcache());
		} else if (ToolCache.getCacheType().equals(ConstantCache.cache_type_redis)) {
			constants.setTokenCache(new FormTokenByRedis());
		}

	}

	/**
	 * 配置处理器
	 */
	@Override
	public void configHandler(Handlers handlers) {
		log.info("configHandler 全局配置处理器，记录日志和request域值处理");
		handlers.add(new GlobalHandler());
		handlers.add(new WebSocketHandler("^/websocket"));

	}

	/**
	 * 配置全局拦截器
	 */
	@Override
	public void configInterceptor(Interceptors interceptors) {
		// log.info("configInterceptor XSS过滤");
		// interceptors.add(new XSSInterceptor());

		log.info("configInterceptor 权限认证拦截器");
		interceptors.add(new AuthInterceptor());

		log.info("configInterceptor 参数封装拦截器");
		interceptors.add(new ParamPkgInterceptor());
		//
		// log.info("configInterceptor 配置开启事物规则");
		// interceptors.add(new TxByMethods("save", "update", "delete"));
		// interceptors.add(new
		// TxByMethodRegex("(.*save.*|.*update.*|.*delete.*)")); //
		// 2.1开始只支持单实例添加，多方法名匹配使用一个正则匹配
		// interceptors.add(new TxByActionKeys("/test/user/save",
		// "/test/user/delete"));
		// interceptors.add(new TxByActionKeyRegex("/test/user.*"));

	}

	/**
	 * 配置插件
	 */
	@Override
	public void configPlugin(Plugins plugins) {
		// ***************************数据源配置**********************************
		DataBase db = ToolDataBase.getDbMap(ConstantInit.db_dataSource_main);
		String db_type = db.getType();

		log.info("configPlugin 配置Druid数据库连接池连接属性");
		DruidPlugin druidPlugin = new DruidPlugin(db.getJdbcUrl(), db.getUserName(), db.getPassWord(),
				db.getDriverClass());

		log.info("configPlugin 配置Druid数据库连接池大小");
		druidPlugin.set(db.getInitialSize(), db.getMinIdle(), db.getMaxActive());

		log.info("configPlugin 配置Druid数据库连接池过滤器配制");
		druidPlugin.addFilter(new StatFilter());
		WallFilter wall = new WallFilter();
		wall.setDbType(db_type);
		WallConfig config = new WallConfig();
		config.setFunctionCheck(false); // 支持数据库函数
		wall.setConfig(config);
		druidPlugin.addFilter(wall);

		log.info("configPlugin 配置ActiveRecordPlugin插件");
		ActiveRecordPlugin arp = new ActiveRecordPlugin(ConstantInit.db_dataSource_main, druidPlugin);

		boolean devMode = Boolean.parseBoolean(PropKit.get(ConstantInit.config_devMode));
		arp.setDevMode(devMode); // 设置开发模式
		arp.setShowSql(devMode); // 是否显示SQL
		arp.setContainerFactory(new CaseInsensitiveContainerFactory(true)); // 大小写不敏感

		// arp.setBaseSqlTemplatePath(PathKit.getRootClassPath()); //
		// 设置sql文件存放的基础路径
		// arp.addSqlTemplate("/com/xpgk/mvc/user/User.sql"); // 添加sql模板

		log.info("configPlugin 使用数据库类型是 mysql");
		arp.setDialect(new MysqlDialect());

		log.info("configPlugin 表自动扫描注册");
		ModelScan.scan(ConstantInit.db_dataSource_main, arp);

		log.info("configPlugin 添加druidPlugin插件");
		plugins.add(druidPlugin);

		log.info("configPlugin 注册ActiveRecordPlugin插件");
		plugins.add(arp);
		// ***************************数据源配置结束**********************************

		log.info("ServicePlugin Service注解实例化加载");
		plugins.add(new ServicePlugin());

		log.info("EhCachePlugin EhCache缓存");
		plugins.add(new EhCachePlugin());

		log.info("configPlugin SqlXmlPlugin 解析并缓存 xml sql");
		plugins.add(new SqlXmlPlugin());

		log.info("configPlugin ParamInitPlugin 缓存参数");
//		plugins.add(new ParamInitPlugin());

		log.info("configPlugin FileRenamePlugin 配置文件上传命名策略插件");
		plugins.add(new FileRenamePlugin());
	}

	/**
	 * 配置路由
	 */
	@Override
	public void configRoute(Routes routes) {
		routes.add("/", IndexController.class); // 首页
		routes.add("/login", LoginController.class); // 登录
		routes.add("/authImg", AuthImgController.class); // 验证码
		routes.add(new ShouBaRoutes());
		routes.add(new AppRoutes());// app

	}

	/**
	 * 系统启动完成后执行
	 */
	public void afterJFinalStart() {
		log.info("afterJFinalStart 启动操作日志入库线程");
		// ThreadSysLog.startSaveDBThread();
	}

	/**
	 * 系统关闭前调用
	 */
	public void beforeJFinalStop() {
		log.info("beforeJFinalStop 释放日志入库线程");
		// ThreadSysLog.setThreadRun(false);
	}

	@Override
	public void configEngine(Engine arg0) {
		// TODO Auto-generated method stub

	}

}
